package com.druid.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.druid.entity.ClashFile;
import com.druid.model.PageBody;
import com.druid.model.ResponseData;
import com.druid.request.PageParam;
import com.druid.request.UploadLinkRequest;
import com.druid.service.managementservice.IClashFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;

/**
 * <p>
 * Clash文件信息表 前端控制器
 * </p>
 *
 * @author example
 * @since 2023-04-01
 */
@Api(tags = "Clash文件管理")
@RestController
@RequestMapping("/clashFile")
public class ClashFileController {

    @Autowired
    private IClashFileService clashFileService;

    @Value("${clash.token}")
    private String clashToken;
    @Value("${clash.store}")
    private String store;

    @ApiOperation("得到上传Clash文件分页列表")
    @PostMapping(value = "getClashFilePageList")
    public ResponseData<PageBody<ClashFile>> getClashFilePageList(@RequestBody @Validated PageParam pageParam ) {

        return ResponseData.SUCCESS(
                PageBody.dealWithIPage(
                        clashFileService.page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()))
                )
        );
    }

    @ApiOperation("根据主键idClash文件")
    @PostMapping(value = "deleteClashFile")
    public ResponseData<String> deleteClashFile (@RequestBody ClashFile info) {

        // 根据id查询文件记录
        ClashFile clashFile = clashFileService.getById(info.getId());

        if (clashFile == null) {
            return ResponseData.FAILURE("文件不存在");
        }

        // 获取文件存储路径
        String storePath = clashFile.getStoreAddress();

        // 删除文件
        if (storePath != null) {
            File file = new File(storePath);
            if (file.exists())file.delete();
        }
        clashFileService.removeById(info.getId());
        return ResponseData.SUCCESS("删除成功");
    }


    @ApiOperation("上传Clash文件链接")
    @PostMapping("/uploadClashFileLink")
    public ResponseData<String> uploadClashFileLink(@RequestBody UploadLinkRequest request) throws IOException {
        String link = request.getLink();
        String source = request.getSource();

        URL url = new URL(link);
        URLConnection connection = url.openConnection();
        String fileName = url.getFile().substring(url.getFile().lastIndexOf("/") + 1);
        String fileType = connection.getContentType();
        long fileSize = connection.getContentLengthLong();

        // 定义文件存储路径
        String storePath = store + fileName;
        File file = new File(storePath);

        // 创建文件输出流
        try (OutputStream outputStream = new FileOutputStream(file)) {
            // 从URL连接读取数据并写入文件
            IOUtils.copy(connection.getInputStream(), outputStream);
        }

        ClashFile clashFile = new ClashFile();
        clashFile.setFileName(fileName);
        clashFile.setFileType(fileType);
        clashFile.setFileSize(fileSize);
        clashFile.setStoreAddress(storePath);
        clashFile.setUrlLink(request.getLink());
        clashFile.setSource(source);
        clashFile.setCreateTime(LocalDateTime.now());
        clashFileService.save(clashFile);

        return ResponseData.SUCCESS("文件链接上传成功");
    }


    @ApiOperation("下载Clash文件")
    @GetMapping("/download/{sourceName}")
    public void downloadClashFile(@PathVariable("sourceName") String sourceName,
                                  @RequestParam("token") String token,
                                  HttpServletResponse response) throws IOException {
        // 验证token
        if (!clashToken.equals(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            return;
        }

        // 根据文件来源查询最新的文件
        ClashFile clashFile = clashFileService.getOne(new QueryWrapper<ClashFile>()
                .eq("source", sourceName)
                .orderByDesc("create_time")
                .last("limit 1"));

        if (clashFile == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        // 获取文件存储路径
        String storePath = clashFile.getStoreAddress();
        File file = new File(storePath);

        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        // 确保文件名以 .yaml 结尾
        String fileName = clashFile.getFileName();
        if (!fileName.toLowerCase().endsWith(".yaml")) {
            fileName = fileName + ".yaml";
        }

        // 设置响应头
        response.setContentType(clashFile.getFileType());
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

        // 读取文件并写入输出流
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }


}